package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 李旭
 * @date 2022/1/17 14:29
 * @Description:
 *   购物车微服务
 *
 */
@RestController
@RequestMapping("/api/cart")
public class CartInfoApiController {

    @Autowired
    private CartInfoService cartInfoService;

    //加入购物车
    @GetMapping("/addCart/{skuId}/{skuNum}")
    public void addCart(@PathVariable Long skuId,@PathVariable Integer skuNum
      ,@RequestHeader(value = "userId",required = false) String userId,
                            @RequestHeader(value = "userTempId" ,required = false) String userTempId){
        System.out.println("userId:" + userId);
        System.out.println("userTempId:" + userTempId);
        //判断用户是否登录
        if(StringUtils.isEmpty(userId)){
            //表示：用户未登录
            cartInfoService.addCart(skuId,skuNum,userTempId);
        }else{
            cartInfoService.addCart(skuId,skuNum,userId);
        }
    }
    //加入购物车 查询
    @GetMapping("/toCart/{sId}/{sNum}")
    public CartInfo toCart(@PathVariable Long sId, @PathVariable Integer sNum, HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            userId = AuthContextHolder.getUserTempId(request);
        }
        return cartInfoService.toCart(sId,sNum,userId);
    }
    //去购物车结算  （查询购物车集合）
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String userTempId = AuthContextHolder.getUserTempId(request);
        System.out.println("userId:" + userId);
        System.out.println("userTempId:" + userTempId);
        List<CartInfo> cartInfoList = cartInfoService.cartList(userId,userTempId);
        return Result.ok(cartInfoList);
    }
    //选中或取消
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked){
        cartInfoService.checkCart(skuId,isChecked);

        return Result.ok();
    }
    //查询选中的购物车
    @GetMapping("/findCartInfoListAndChecked")
    public List<CartInfo> findCartInfoListAndChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        return cartInfoService.findCartInfoListAndChecked(userId);

    }

}
